<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <h1 id="count">1</h1>
    <button id="btn">add</button>
  </div>

  <script>
    const btn = document.getElementById('btn')
    const h1 = document.getElementById('count')

    let obj = {
      count: 1
    }

    watch(obj, 'count', (newVal, oldVal) => {
      console.log(123);
    })

    // 手写 watch
    function watch(obj, key, cb) {
      let value = obj[key]
      Object.defineProperty(obj, key, {
        get() {
          return value
        },
        set(newValue) {
          cb(newValue, value)
          value = newValue
        }
      })
    }

    btn.addEventListener('click', () => {
      obj.count++
    })

    // let value = obj.count
    // Object.defineProperties(obj, 'count', {
    //   get() {
    //     return value
    //   },
    //   set(newVal) {
    //     value = newVal
    //     h1.innerHTML = newVal
    //   }
    // })
  </script>
</body>
</html>